import { uploadFile } from '@/api/base'
import { ElMessage } from 'element-plus'

// 处理文件上传
export const handleFileUpload = async (file, callback) => {
  const formData = new FormData()
  formData.append('file', file)
  
  try {
    const response = await uploadFile(formData)
    if (response && response.Success) {
      ElMessage.success('上传成功')
      if (callback && typeof callback === 'function') {
        callback(response.Data)
      }
      return response.Data
    } else {
      ElMessage.error(response?.Message || '上传失败')
      return null
    }
  } catch (error) {
    ElMessage.error('上传失败')
    console.error('文件上传错误:', error)
    return null
  }
}

// 处理条款选择
export const handleTermSelect = (termId, termList, row) => {
  if (!termId || !termList || !row) return
  
  const selectedTerm = termList.find(term => 
    term.Id.toLowerCase().includes(termId.toLowerCase())
  )

  if (selectedTerm) {
    row.TermContent = selectedTerm.Content
  }
}

// 添加表格行
export const addTableRow = (tableData, initialData = {}) => {
  const newRow = {
    LineNum: tableData.length + 1,
    ...initialData
  }
  tableData.push(newRow)
  return newRow
}

// 删除表格行
export const deleteTableRow = (tableData, index) => {
  if (index >= 0 && index < tableData.length) {
    tableData.splice(index, 1)
    // 重新计算行号
    tableData.forEach((row, idx) => {
      row.LineNum = idx + 1
    })
  }
}